from leapp.libraries.common.config.version import get_target_major_version, is_rhel_realtime
from leapp.libraries.stdlib import api, CalledProcessError, run
from leapp.models import InstalledTargetKernelVersion
import re,os,time

def _get_newest_kernel_version():
    if os.path.exists('/etc/yum.repos.d/leapp-upgrade-repo-oc.repo'):
        with open('/etc/yum.repos.d/leapp-upgrade-repo-oc.repo', 'r') as file:
                content = file.read()
        content = content.replace('$releasever','9.0')
        with open('/etc/yum.repos.d/leapp-upgrade-repo-oc.repo', 'w') as file:
                file.write(content)
        time.sleep(1)
        command = ["yum", "--showduplicates", "--disablerepo=*","--releasever=9.0", "--enablerepo=baseos-rpms,appstream-rpms", "list", "kernel-core"]
        output = run(command, split=True)
        filtered_output = [line for line in output['stdout'] if 'kernel-core' in line]
        number_of_kernelcore = len(filtered_output)
        original_version = filtered_output[number_of_kernelcore-1] if filtered_output else None
        if 'oc9' in original_version:
            part_version = original_version.split()[1]
            kernel_version=part_version.split(".oc9")
            print("kernel_version:",kernel_version)
            return kernel_version[0]

def process():
    # pylint: disable=no-else-return  - false positive
    # TODO: should we take care about stuff of kernel-rt and kernel in the same
    # time when both are present? or just one? currently, handle only one
    # of these during the upgrade. kernel-rt has higher prio when original sys

    version = _get_newest_kernel_version()
    if version:
        print(version)
        api.produce(InstalledTargetKernelVersion(version=version))
    else:
        # This is very unexpected situation. At least one kernel has to be
        # installed always. Some actors consuming the InstalledTargetKernelVersion
        # will crash without the created message. I am keeping kind of original
        # behaviour in this case, but at least the let me log the error msg
        #
        api.current_logger().error('Cannot detect any kernel RPM')
        # StopActorExecutionError('Cannot detect any target RHEL kernel RPM.')
